//
//  LiuTabBar.swift
//  LiuWeiBo
//
//  Created by 刘晓晨 on 2017/3/26.
//  Copyright © 2017年 刘晓晨. All rights reserved.
//

import UIKit

protocol LiuTabBarDelegate:NSObjectProtocol {
    
    func composeButtonAction()
}

class LiuTabBar: UITabBar {
    //懒加载button
    lazy var composeButton: UIButton = {
        let button = UIButton()
        
        //设置不同状态按钮图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        //给composeButton添加点击事件
        button.addTarget(self, action: #selector(composeBuutonAction), for: .touchUpInside)
        
        return button
    }()
    
    //设置composeButton点击的代理回调
    weak var cmoposeDelegate:LiuTabBarDelegate?

    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setuoUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setuoUI() {
        
        //设置背景图片,防止隐藏tabbar背景变黑
        backgroundImage = UIImage(named: "tabbar_background")
        
        //添加按钮
        addSubview(composeButton)
        composeButton.sizeToFit()
    }
    
    //给分栏和按钮布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //每个按钮的宽度
        let widgetWidth = self.width / 5
        
        //按钮的中心位置
        composeButton.centerX = width * 0.5
        composeButton.centerY = height * 0.5
        
        //创建一个标示
        var index = 0
        
        //循环遍历子控件设置位置
        for subView in subviews {
            
            //判断subView是否是tabbaritem类型
            if subView.isKind(of: NSClassFromString("UITabBarButton")!) {
                subView.x = CGFloat(index) * widgetWidth
                subView.width = widgetWidth
                index += 1
                if index == 2 {
                    index += 1
                }
            }
        }
        
    }
    
    
    func composeBuutonAction() {
        cmoposeDelegate?.composeButtonAction()
    }

    
    
    
}
